
package com.oa.modules.sys.controller;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.common.utils.DateUtils;
import com.oa.common.utils.R;
import com.oa.modules.approvalsec1.entity.BiddProjectEntity;
import com.oa.modules.approvalsec1.service.BiddProjectService;
import com.oa.modules.sys.entity.SysDeptEntity;
import com.oa.modules.sys.entity.SysRoleEntity;
import com.oa.modules.sys.entity.SysUserEntity;
import com.oa.modules.sys.entity.SysUserRoleEntity;
import com.oa.modules.sys.form.SysLoginForm;
import com.oa.modules.sys.service.*;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author sunhui
 */
@RestController
@Api(tags = "用户登录相关接口")
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    @ApiOperation(value = "验证码获取接口", notes = "uuid是一个随机字符串")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "随机字符串", required = true, paramType = "query")
    })
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    @ApiOperation(value = "登录接口")
    public Map<String, Object> login(@RequestBody @ApiParam(value = "登录") SysLoginForm form) throws IOException {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return R.error("验证码不正确");
        }

        // 用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());
        QueryWrapper<SysUserRoleEntity> wrapper = new QueryWrapper<SysUserRoleEntity>().eq("user_id", user.getUserId());
        SysUserRoleEntity sysUserRoleEntity = sysUserRoleService.list(wrapper).get(0);


        //账号不存在、密码错误
        //if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
        //	return R.error("账号或密码不正确");
        //}

        // 账号不存在、密码错误
        if (user == null || !user.getPassword().equals(form.getPassword())) {
            return R.error("账号或密码不正确");
        }

        // 账号锁定
        if (user.getStatus() == 1) {
            return R.error("账号已被锁定,请联系管理员");
        }

        // 非管理员用户不能登录后台管理页面
//        if (sysUserService.validatorUserRole(user)) {
//            return R.error("非管理员用户不可登录!");
//        }

        //生成token，并保存到数据库
        SysDeptEntity dept = sysDeptService.getById(user.getDeptId());
        if (dept != null && !StringUtils.isBlank(dept.getDeptId())) {
            user.setDeptId(dept.getDeptId());
        }
        R r = sysUserTokenService.createToken(user.getUserId());
        return r.put("user", user).put("dept", dept).put("roleId",sysUserRoleEntity.getRoleId());
    }

    /**
     * 登录
     */
    @PostMapping("/sys/loginWeb")
    @ApiOperation(value = "登录接口")
    public Map<String, Object> loginWeb(@RequestBody @ApiParam(value = "登录") SysLoginForm form) throws IOException {
        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(form.getPassword())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 1) {
            return R.error("账号已被锁定,请联系管理员");
        }

        // 先获取用户的部门根据部门的租户id查询企业信息
        SysDeptEntity dept = sysDeptService.getById(user.getDeptId());

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        return r.put("user", user).put("dept", dept);
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

}
